package com.vitabuybuy.tv.ui.auth

import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.RegexUtils
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.HeadInterceptor
import com.library.common.toast.XToast
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.BuildConfig
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityEmailLoginBinding
import com.vitabuybuy.tv.ui.MainActivity
import com.vitabuybuy.tv.ui.auth.viewmodel.AuthViewModel
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.LoginInfo
import com.vitabuybuy.tv.utils.StringUtil
import kotlinx.android.synthetic.main.activity_email_login.*

class EmailLoginActivity : BaseActivity<AuthViewModel,ActivityEmailLoginBinding>(){
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_email_login

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.login))
    }

    override fun eventHandling() {
        setOnclickNoRepeat(ivEye, tvForgetPassword, btnLogin){v->
            when (v) {
                ivEye -> {
                    if (etPassword.transformationMethod == HideReturnsTransformationMethod.getInstance()) {
                        etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
                        ivEye.setImageResource(R.drawable.icon_login_eyes_n)
                    } else {
                        etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
                        ivEye.setImageResource(R.drawable.icon_login_eyes)
                    }
                }
                tvForgetPassword -> {
                    BindEmailActivity.openActivity(mContext, bundleOf(Pair("from",BindEmailActivity.FROM_EMAIL_FORGET_PWD)))
                }
                btnLogin -> {
                    if (etEmail.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_email))
                        return@setOnclickNoRepeat
                    }
                    if (!RegexUtils.isEmail(etEmail.text)) {
                        XToast.normal(getString(R.string.please_enter_correct_email))
                        return@setOnclickNoRepeat
                    }
                    if (etPassword.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_password))
                        return@setOnclickNoRepeat
                    }
                    if (!StringUtil.judgePassword(etPassword.text.toString())) {
                        XToast.normal(getString(R.string.password_dialog_tip))
                        return@setOnclickNoRepeat
                    }
                    viewModel.loginByEmailAndPwd(etEmail.text.toString(),etPassword.text.toString())
                }
            }
        }
    }

    override fun observeData() {
        viewModel.tokenInfo.observe(this, Observer {
            HeadInterceptor.sessionId = it.token
            mmkv.encode(MMKVContancts.SESSIONID, it.token)
            mmkv.encode(MMKVContancts.USER_PHONE, it.phone.split("-")[1])
            mmkv.encode(MMKVContancts.IS_LOGIN_IN, true)
            viewModel.getUserInfo()
        })
        viewModel.userInfoDto.observe(this, Observer {
            val loginInfo = LoginInfo().apply {
                sdkAppID = BuildConfig.LIVEAPPID.toLong()
                userID = it.id.toString()
                userSig = it.userSign
                userName = it.nickname
                userAvatar = it.avatar
            }
            MLVBLiveRoom.sharedInstance(appContext)
                .login(loginInfo, object : IMLVBLiveRoomListener.LoginCallback {
                    override fun onSuccess() {
                        mmkv.encode(MMKVContancts.USER_EMAIL, it.email)
                        mmkv.encode(MMKVContancts.USER_ID, it.id)
                        mmkv.encode(MMKVContancts.USER_SIGN, it.userSign)
                        mmkv.encode(MMKVContancts.USER_ID, it.id)
                        mmkv.encode(MMKVContancts.USER_SIGN, it.userSign)
                        MainActivity.openActivity(mContext)
                    }

                    override fun onError(errCode: Int, errInfo: String?) {
                        errInfo?.run {
                            errCode.logE("JIA--errCode--")
                            this.logE("JIA--errInfo--")
                            XToast.error("直播登录失败，请联系管理员")
                        }
                    }
                })
        })
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            7 -> {
                HeadInterceptor.sessionId = msg.obj as String
                viewModel.getUserInfo()
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, EmailLoginActivity::class.java)
        }
    }
}
